#!/bin/bash
# Author    : MoShangSan
# create_ts : 2022-05-15
# program   : Compile Code, Convert DOS/Mac text file format into Unix, Tar package
bash_path=$(cd `dirname $0`; pwd)
CURRENT_PATH=$(cd ${bash_path}/..; pwd)
INSTALL_PATH=${CURRENT_PATH}/output
CURRENT_TIME=$(date "+%Y%m%d_%H%M")
LOG_FILE=${CURRENT_PATH}/log/$(date "+%Y%m%d%H%M%S").log
SHELL_NAME="build.sh"

SOURCE_DIR=$1
CODECHECK_DIR=$2
JENKINS_URL=$3
USERNAME=$4
PASSWORD=$5

# GIT_USER_NAME=$4
# GIT_USER_EMAIL=$5
# GIT_USER_PASSWORD=$6

function LOG() {
    USER=$(whoami) ####那个用户在操作
    if [ ! -e ${CURRENT_PATH}/log ];then
       mkdir ${CURRENT_PATH}/log
    fi
    if [ ! -f ${LOG_FILE} ];then
       touch ${LOG_FILE}
    fi
    echo "[${DATE}] ${USER} [$1][$SHELL_NAME]$2"
    echo "[${DATE}] ${USER} [$1][$SHELL_NAME]$2" >> ${LOG_FILE}  ######（$0脚本本身，$@将参数作为整体传输调用, >> 将输出结果以追加的方式添加重定向到本地文件中）
}

function dos_to_unix() {
    # Convert DOS/Mac text file format into Unix under built-in `dos2unix` handler.
        # $1: OS directory path
    local path="$1"
    local path=${path%/}
    local IFS=$'\n'
    # shellcheck disable=SC2045
    for obj in $(ls "${path}")
    do
        if [[ -d "${path}/${obj}" ]]; then
            dos_to_unix "${path}/${obj}"
        else
            dos2unix "${path}/${obj}"
        fi
    done
}

LOG INFO "--Start build.sh --------"
# 代码检查
cd ${CURRENT_PATH}
mkdir -p output
mkdir -p ${CODECHECK_DIR}/codecheck/${CURRENT_TIME}
pylint -f parseable src/  -d I0011,R0801 --evaluation="error + warning + refactor + convention"| tee output/pylint.xml
mv output/pylint.xml ${CODECHECK_DIR}/codecheck/${CURRENT_TIME}/pylint.xml
LOG INFO "Pylint Finish"

sloccount --duplicates --details ${CURRENT_PATH}/src > ${CODECHECK_DIR}/codecheck/${CURRENT_TIME}/sloccount_.sc
LOG INFO "Sloccount Finish"
# git config --global user.name ${GIT_USER_NAME}
# git config --global user.email ${GIT_USER_EMAIL}
# git config --global user.password ${GIT_USER_PASSWORD}
# git add .
# git commit -a -m "代码检查结果提交"
# git push

# 打包、安装和启动
bash ${CURRENT_PATH}/package.sh ${SOURCE_DIR} ${CODECHECK_DIR}
bash ${CURRENT_PATH}/install.sh
cd ${CURRENT_PATH}/../
mkdir -p log
# bash CURRENT_PATH/start.sh ${USERNAME} ${PASSWORD}

# 消息发送
# 钉钉机器人
curl 'https://oapi.dingtalk.com/robot/send?access_token=336c1f1fed433d8e5e9acc6460be1f361b37699ac10614ab37d12d970ac556dc' \
-H 'Content-Type: application/json' \
-d '{"msgtype": "markdown", \
    "markdown": { "title":"Jenkins",  "text": "#### Jenkins \n > 代码构建已完成：详见地址：$JENKINS_URL\n > ###### $(date "+%H时%M分") \n" } \
  }'
# vocechat聊天机器人                  
bash chat_robot/chat_robot.sh "jenkins" "代码构建已完成：详见地址：$JENKINS_URL"